<template>
  <div class="container mx-auto p-4">
    <h1 class="text-2xl font-bold mb-4">数据表格</h1>
    <div class="flex mb-4">
      <button @click="fetchData('database')" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded mr-2">
        从数据库获取数据
      </button>
      <button @click="fetchData('excel')" class="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded">
        从Excel获取数据
      </button>
    </div>
    <div class="overflow-x-auto">
      <table class="min-w-full bg-white">
        <thead>
          <tr class="bg-gray-800 text-white">
            <th class="py-3 px-4 text-left">ID</th>
            <th class="py-3 px-4 text-left">名称</th>
            <th class="py-3 px-4 text-left">类型</th>
            <th class="py-3 px-4 text-left">价格</th>
            <th class="py-3 px-4 text-left">日期</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in tableData" :key="item.id" class="border-b border-gray-200 hover:bg-gray-100">
            <td class="py-3 px-4">{{ item.id }}</td>
            <td class="py-3 px-4">{{ item.name }}</td>
            <td class="py-3 px-4">{{ item.type }}</td>
            <td class="py-3 px-4">{{ item.price }}</td>
            <td class="py-3 px-4">{{ item.date }}</td>
          </tr>
        </tbody>
      </table>
    </div>
    <div v-if="loading" class="mt-4 text-center">
      <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
      <p class="mt-2">加载中...</p>
    </div>
    <div v-if="error" class="mt-4 p-4 bg-red-100 text-red-700 rounded">
      {{ error }}
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'

const tableData = ref([])
const loading = ref(false)
const error = ref(null)

const fetchData = async (sourceType) => {
  loading.value = true
  error.value = null
  
  try {
    const response = await axios.get(`/api/table-data?source=${sourceType}`)
    tableData.value = response.data
  } catch (err) {
    error.value = err.message || '获取数据失败'
  } finally {
    loading.value = false
  }
}

// 初始加载数据库数据
onMounted(() => {
  fetchData('database')
})
</script>

<style scoped>
.container {
  max-width: 1200px;
}
</style>    